<!--围栏地图页-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">新增围栏</span>
    <el-button type="primary" style="float:right;margin-top:13px;"
               @click="router.push('/geofence')">返回
    </el-button>
  </div>
  <!-- 定义一个div充当地图容器-->
  <div id="mapContainer" style="width: 100%;height: 84vh;"></div>
  <!--新增电子围栏弹窗   -->
  <el-dialog title="围栏信息" v-model="dialogVisible" :before-close="closeDialog">
    <el-form>
      <el-form-item label="围栏名称">
        <el-input placeholder="请输入围栏名称" v-model="geofence.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="saveGeofence">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import router from "@/router";
import {nextTick, onMounted, ref} from "vue";
import {DrawScene, DrawControl, OperateEventType} from 'bmap-draw';
import {ElMessage} from "element-plus";
import qs from "qs";
import axios from "axios";
//定义一个用来保存围栏数据的对象，后续给后端发送请求使用
const geofence = ref({
  name: '',
  position: {}
});
//定义变量控制围栏名称弹窗是否可见
const dialogVisible = ref(false);
//定义全局变量
var map;
onMounted(() => {
  //表示DOM更新之后才执行，因为我们需要确保上方地图容器div创建之后再给div里渲染地图
  nextTick(() => {
    //第7步：创建地图实例，注意不要引入，忽略提示
    map = new BMapGL.Map("mapContainer");
    //第8步：设置中心点坐标，设置经纬度
    let point = new BMapGL.Point(116.4074, 39.9024);
    //第9步：设置地图显示的中心点与地图缩放级别
    map.centerAndZoom(point, 15);
    // 添加鼠标绘制控件
    //1.创建鼠标绘制场景类，此类为基类，可以进行事件监听与覆盖物的存取，注意：需要导入
    const scene = new DrawScene(map);
    //2.创建鼠标绘制控件类，可以基于上方的绘制场景进行一些自定义的设置
    const drawControl = new DrawControl(scene, {
      //3.设置是否显示提示信息
      enableTips: false,
      //4.设置控件的位置
      anchor: BMAP_ANCHOR_TOP_RIGHT,
      //5.设置可以绘制的图形 circle圆形 rectangle矩形
      drawingItems: [
        'marker',
        'polyline',
        'polygon',
        'circle',
        'rectangle'
      ]
    });
    //7.监听绘制完成事件(打对勾)，返回的是触发此事件的图形对象
    scene.addEventListener(OperateEventType.COMPLETE, (event) => {
      /*用户一点✓，就让弹窗出现*/
      dialogVisible.value = true;
      //target就是触发此事件的目标对象，也就是我们的围栏对象
      console.log(event.target);
      //8.获取覆盖物，也就是圆形/矩形围栏对象
      let overlay = event.target.overlay;
      console.log(overlay);
      //9.判断当前围栏是圆形还是矩形，分别处理
      if (overlay instanceof BMapGL.Circle) {
        geofence.value.position.type = 'circle';
        geofence.value.position.radius = overlay.getRadius();
        geofence.value.position.longitude = overlay.getCenter().lng;
        geofence.value.position.latitude = overlay.getCenter().lat;
        console.log(geofence.value);
      } else {
        geofence.value.position.type = 'rectangle';
        //定义数组用来保存矩形的四个顶点坐标
        let recPoints = [];
        //循环获取覆盖物的四个顶点，以经度-纬度拼接，并存入上方的空数组中
        for (var i = 0; i <= 3; i++) {
          recPoints.push(
              overlay.points[i].latLng.lng + '-'
              + overlay.points[i].latLng.lat
          );
        }
        //将准备好的顶点数组转为字符串
        geofence.value.position.recPoints = recPoints.join(',');
        console.log(geofence.value);
      }
    })
    //6.将配置好的鼠标绘制控价添加到地图中
    map.addControl(drawControl);
  })
})
//定义保存围栏的方法
const saveGeofence = () => {
  if (!geofence.value.name || geofence.value.name.trim() == '') {
    ElMessage.error('请输入围栏名称！');
    return;
  }
  console.log(geofence.value);
//由于position属性是对象，所以需要先将其转为JSON字符串，再将geofence转为查询字符串
  geofence.value.position=JSON.stringify(geofence.value.position);
  let data = qs.stringify(geofence.value);
  console.log(data);
  axios.post(BASE_URL+'/v1/geofence/save',data).then((response)=>{
    if (response.data.code==2000){
      ElMessage.success('保存成功');
      dialogVisible.value=false;
      router.push('/geofence');
    }else {
      ElMessage.error(response.data.msg);
    }
  })

}
//定义关闭弹窗的方法
const closeDialog = () => {
  if (confirm('您确定要关闭弹窗吗？')) {
    dialogVisible.value = false;
    map.clearOverlays();
    geofence.value = {
      name: '',
      position: {}
    };
  }
}
</script>

<style scoped>

</style>